<template>
  <div class="box">
    <div class="left">
      <el-tree
        :data="tree"
        ref="tree"
        node-key="id"
        :current-node-key="nodeKey"
        :props="{ label: 'name' }"
        highlight-current
        default-expand-all
        :expand-on-click-node="false"
        @node-click="nodeClick"
      >
        <span class="treeNode" slot-scope="{ node, data }">
          <span>{{ node.label }}</span>
          <el-dropdown
            trigger="click"
            @command="(cmd) => handleCommand(cmd, node, data)"
          >
            <i class="el-icon-more"></i>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="add">添加节点</el-dropdown-item>
              <el-dropdown-item v-if="data.id > 0" command="edit"
                >编辑节点</el-dropdown-item
              >
              <el-dropdown-item v-if="data.id > 0" command="remove"
                >删除节点</el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
        </span>
      </el-tree>
      <el-dialog
        width="300px"
        title="节点提交"
        :visible.sync="dialogFormVisible"
      >
        <el-form :model="form">
          <el-form-item label="名称">
            <el-input v-model="form.name"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <div class="right">
      <div class="action">
        <!-- -->
        <el-button
            v-if="nodeKey == 0"
            type="primary"
            icon="el-icon-user"
            size="small"
            @click="addRegisterUser"
        >创建用户</el-button
        >
        <!-- -->
        <el-button
          v-if="nodeKey > 0"
          type="primary"
          icon="el-icon-user"
          size="small"
          @click="addUser"
          >添加成员</el-button
        >
      </div>
      <el-table :data="groupUsers" stripe style="width: 100%">
        <el-table-column prop="userId" label="用户主键" align="center">
        </el-table-column>
        <el-table-column align="center" label="用户名">
          <template slot-scope="scope"
            ><i
              class="el-icon-star-on"
              :style="{ color: 'red' }"
              v-if="scope.row.boss"
              title="主管"
            ></i
            >{{ scope.row.userName }}</template
          >
        </el-table-column>
        <el-table-column align="center" label="是否主管">
          <template slot-scope="scope">{{
            scope.row.boss ? "是" : "否"
          }}</template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="100">
          <template slot-scope="scope">
            <el-button
              v-if="nodeKey === 0"
              @click="setBoss(scope.row)"
              type="text"
              size="small"
              >{{ `${scope.row.boss ? "取消" : "设置"}主管` }}</el-button
            >

            <el-button
              v-else
              @click="removeUser(scope.row)"
              type="text"
              size="small"
              >移除成员</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-dialog
        width="600px"
        title="用户提交"
        :visible.sync="dialogUsersVisible"
      >
        <el-table
          ref="multipleTable"
          :data="users"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column prop="userId" label="用户主键" align="center">
          </el-table-column>
          <el-table-column prop="userName" align="center" label="用户名">
          </el-table-column>
        </el-table>
        <div slot="footer">
          <el-button @click="dialogUsersVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitUsers">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 新建用户 begin -->
      <el-dialog
          width="600px"
          title="新建用户"
          :visible.sync="dialogAddUsersVisible"
      >
        <div class="form">
          <label>
            <span>用户名</span>
            <input type="text" v-model="registerForm.username" @keyup.enter="doRegister" ref="username"/>
          </label>
          <label>
            <span>密码</span>
            <input type="password" v-model="registerForm.password" @keyup.enter="doRegister"/>
          </label>
          <label>
            <span>确认密码</span>
            <input type="password" v-model="registerForm.rePassword" @keyup.enter="doRegister"/>
          </label>
          <label>
            <span>密保问题</span>
            <input type="text" v-model="registerForm.question" @keyup.enter="doRegister"/>
          </label>
          <label>
            <span>密保答案</span>
            <input type="text" v-model="registerForm.answer" @keyup.enter="doRegister"/>
          </label>
          <el-button type="warning" class="submit" :loading="loading" @click="doRegister" round>注 册</el-button>
        </div>
      </el-dialog>
      <!-- 新建用户 end -->
    </div>
  </div>
</template>

<script>
import _ from "lodash";
import groupService from "../../api/group";

// register begin
import panUtil from '../../utils/common'
import userService from '../../api/user'
//

export default {
  data() {
    return {
      tree: [
        {
          id: 0,
          name: "根节点",
          children: [],
        },
      ],
      nodeKey: 0,
      dialogFormVisible: false,
      form: {
        name: "",
      },
      users: [],
      groupUsers: [],
      dialogUsersVisible: false,
      dialogAddUsersVisible: false,
      multipleUsersSelected: [],
      // register
      loading: false,
      registerForm: {
        username: '',
        password: '',
        rePassword: '',
        question: '',
        answer: '',
      }
    };
  },
  beforeMount() {
    // 获取所有用户
    groupService.users(
      (res) => {
        this.users = res.data;
        this.groupUsers = res.data;
      },
      (res) => {
        this.$message.error(res.message);
      }
    );

    // 获取所有组的树形菜单
    this.getGroupTree();
  },
  methods: {
    getGroupTree() {
      // 获取所有组的树形菜单
      groupService.groupTree(
        (res) => {
          if (res.status === 0) {
            this.tree[0].children = res.data;
          }
        },
        (res) => {
          this.$message.error(res.message);
        }
      );
    },
    handleCommand(command, node, data) {
      if (command === "add") {
        this.dialogFormVisible = true;
        this.form = {
          parentId: data.id,
          id: 0,
          name: "",
        };
      } else if (command === "edit") {
        this.dialogFormVisible = true;
        this.form = {
          parentId: 0,
          id: data.id,
          name: data.name,
        };
      } else if (command === "remove") {
        groupService.deleteGroup(
          data.id,
          () => {
            this.getGroupTree();
          },
          (res) => {
            this.$message.error(res.message);
          }
        );
      }
    },
    submitForm() {
      const { parentId, id, name } = this.form;
      if (id > 0) {
        console.log("编辑节点", `id:${id},name:${name}`);
        groupService.editGroup(
          { id, name },
          () => {
            this.getGroupTree();
          },
          (res) => {
            this.$message.error(res.message);
          }
        );
      } else {
        console.log("添加节点", `parentId:${parentId},name:${name}`);
        groupService.addGroup(
          { parentId, name },
          () => {
            this.getGroupTree();
          },
          (res) => {
            this.$message.error(res.message);
          }
        );
      }
    },
    nodeClick(node) {
      this.nodeKey = node.id;
    },
    getGroupUsers(groupId) {
      groupService.groupUsers(
        groupId,
        (res) => {
          if (res.status === 0) {
            this.groupUsers = res.data;
          }
        },
        (res) => {
          this.$message.error(res.message);
        }
      );
    },
    removeUser(user) {
      const groupId = this.nodeKey;
      groupService.deleteGroupUser(
        { groupId, userId: user.userId },
        () => {
          this.getGroupUsers(groupId);
        },
        (res) => {
          this.$message.error(res.message);
        }
      );
    },
    addUser() {
      this.dialogUsersVisible = true;
      const checkedList = _.reduce(
        this.groupUsers,
        (arr, o) => {
          arr.push(o.userId);
          return arr;
        },
        []
      );

      this.users.forEach((item) => {
        let checked = false;
        if (_.includes(checkedList, item.userId)) {
          checked = true;
        }
        this.$nextTick(() => {
          this.$refs.multipleTable.toggleRowSelection(item, checked);
        });
      });
    },
    addRegisterUser() {
      this.dialogAddUsersVisible = true
    },
    handleSelectionChange(val) {
      this.multipleUsersSelected = val;
    },
    submitUsers() {
      const groupId = this.nodeKey;
      groupService.addGroupUsers(
        {
          groupId,
          userIds: _.map(this.multipleUsersSelected, "userId"),
        },
        () => {
          this.getGroupUsers(groupId);
        },
        (res) => {
          this.$message.error(res.message);
        }
      );
    },
    setBoss(user) {
      const that = this;
      groupService.setUserBoss(
        user.userId,
        (res) => {
          if (res.status === 0) {
            const list = [...that.groupUsers];
            const _user = _.find(list, { userId: user.userId });
            _user.boss = !_user.boss;
            that.groupUsers = list;
          }
        },
        (res) => {
          this.$message.error(res.message);
        }
      );
    },
    // register begin
    doRegister() {
      this.dialogAddUsersVisible = true
      let _this = this
      if (_this.checkRegisterForm()) {
        _this.loading = true
        userService.register(this.registerForm, () => {
          _this.$message.success('注册成功！')
          _this.loading = false
          _this.dialogAddUsersVisible = false
          // flush user list
          groupService.users(
              (res) => {
                this.users = res.data;
                this.groupUsers = res.data;
              },
              (res) => {
                this.$message.error(res.message);
              }
          );
          //
        }, res => {
          _this.$message.error(res.message)
          _this.loading = false
          _this.dialogAddUsersVisible = false
        })
      }
    },
    checkRegisterForm() {
      if (!panUtil.checkUsername(this.registerForm.username)) {
        this.$message.error('请输入6-16位只包含数字和字母的用户名')
        return false
      }
      if (!panUtil.checkPassword(this.registerForm.password)) {
        this.$message.error('请输入8-16位的密码')
        return false
      }
      if (!this.registerForm.rePassword || this.registerForm.password !== this.registerForm.rePassword) {
        this.$message.error('两次密码输入不一致')
        return false
      }
      if (!this.registerForm.question) {
        this.$message.error('请输入密保问题')
        return false
      }
      if (!this.registerForm.answer) {
        this.$message.error('请输入密保答案')
        return false
      }
      return true
    }
    // register end
  },
  watch: {
    nodeKey(newV) {
      if (newV === 0) {
        this.groupUsers = this.users;
      } else {
        this.getGroupUsers(newV);
      }
    },
  },
};
</script>

<style scoped>
*,
*:before,
*:after {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

.box {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: space-between;
  background-color: #fff;
}

.left {
  width: 300px;
}

.treeNode {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.right {
  flex: 1;
  padding: 0 4px;
  border-left: 1px solid #dedede;
}

.action {
  text-align: right;
  margin: 10px 0;
}

/* register begin */
/*.form {*/
/*  position: relative;*/
/*  width: 640px;*/
/*  height: 100%;*/
/*  transition: -webkit-transform 0.6s ease-in-out;*/
/*  transition: transform 0.6s ease-in-out;*/
/*  transition: transform 0.6s ease-in-out, -webkit-transform 0.6s ease-in-out;*/
/*  padding: 50px 30px 0;*/
/*}*/

.form input {
  border: none;
  outline: none;
  background: none;
  font-family: 'Open Sans', Helvetica, Arial, sans-serif;
}

.form button {
  display: block;
  margin: 0 auto;
  width: 260px;
  height: 36px;
  border-radius: 30px;
  color: #fff;
  font-size: 15px;
  cursor: pointer;
}

/*.form h2 {*/
/*  width: 100%;*/
/*  font-size: 26px;*/
/*  text-align: center;*/
/*}*/

.form label {
  display: block;
  width: 260px;
  margin: 25px auto 0;
  text-align: center;
}

.form label span {
  font-size: 12px;
  /*color: #909399;*/
  text-transform: uppercase;
}

.form input {
  display: block;
  width: 100%;
  margin-top: 5px;
  padding-bottom: 5px;
  font-size: 16px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.4);
  text-align: center;
}

.form .submit {
  margin-top: 40px !important;
}

/* */
</style>
